<template>
  <div class="login" id="login-app">
    <el-text class="login-title">汽车租赁</el-text>
    <div class="login-box">
      <img class="login-img" src="../assets/image/login.png" />
      <div class="login-form">
        <el-form :model="loginForm" status-icon :rules="rules" ref="loginFormRef">
          <h2>登录</h2>
          <el-form-item label="账号" prop="username">
            <el-input v-model="loginForm.username" type="useranme" placeholder="请输入用户名" />
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model="loginForm.password" type="password" placeholder="请输入密码" />
          </el-form-item>
          <el-form-item class="login-button" style="margin-bottom:10px">
            <el-button type="primary" @click="toLogin()">登录</el-button>
          </el-form-item>
          <el-form-item class="login-button">
            <el-button type="warning" @click="toRegister()">注册</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import { login, me } from '@/api'
import router from '@/router'
import { FormInstance, ElMessage, FormRules } from 'element-plus'
import axios from 'axios';

const loginForm = reactive({
  username: '',
  password: '',
})

const loginFormRef = ref<FormInstance>();

const validateUsername = (rule: any, value: any, callback: any) => {
  if (!value.trim()) {
    callback(new Error('账号不能为空'))
  } else {
    callback()
  }
}

const validatePassword = (rule: any, value: any, callback: any) => {
  if (!value.trim()) {
    callback(new Error('密码不能为空'))
  } else {
    callback()
  }
}


const rules = reactive<FormRules<typeof loginForm>>({
  username: [{ validator: validateUsername, trigger: 'blur' }],
  password: [{ min: 4, max: 32, message: '密码长度应为4~32字符之间', trigger: 'blur' },
  { validator: validatePassword, trigger: 'blur' }],
})

const toLogin = () => {
  if (loginFormRef.value) {
    loginFormRef.value.validate((valid: boolean) => {
      if (valid) {
        login(loginForm).then((resp: { data: any; }) => {
          let data = resp.data;
          if (data.code == '50051') {
            Object.assign(loginForm, { username: '', password: '' });
            console.log(data);
            localStorage.setItem('token', data.data);
            ElMessage({
              message: data.message,
              type: 'success'
            });
            axios.get('http://localhost:8081/user/me', {
              headers: {
                Authorization: 'Bearer ' + localStorage.getItem('token'),
              }
            }).then((resp: { data: any }) => {
              let data = resp.data;
              console.log(data);
              if (data.code == '50041') {
                if (data.data.type == 0) {
                  setTimeout(() => {
                    window.location.reload();
                  }, 1000);
                  router.push({ path: '/index' })
                }
                else {
                  setTimeout(() => {
                    window.location.reload();
                  }, 1000);
                  router.push({ path: '/' })
                }
              }
            })
          } else {
            Object.assign(loginForm, { username: '', password: '' });
            console.log(data);
            ElMessage({
              message: data.message,
              type: 'error'
            });
          }
        });
      }
    });
  }
};

const toRegister = () => {
  router.push({ path: '/register' })
}
</script>

<style scoped>
.login {
  justify-content: center;
  align-items: center;
  height: 97vh;
  overflow-y: hidden;
  background-color: rgb(237, 237, 237);
}

.login-box {
  display: flex;
  position: absolute;
  left: 10%;
  top: 15%;
}

.login-title {
  position: relative;
  font-size: 50px;
  letter-spacing: 10px;
  font-weight: bolder;
  font-style: italic;
  color: #4971ab;
  top: 20px;
}

.login-form {
  border-radius: 0px 8px 8px 0px;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: rgb(247, 247, 247);
  width: 400px;
  height: 300px;
  margin-left: 5%;
  margin-top: 10%;
  margin-bottom: 5%;
}

.login-img {
  width: 50%;
  height: 80%;
}

.el-form-item {
  line-height: 40px;
  margin-bottom: 15px;
  width: 300px;
}

.el-input {
  max-width: 300px;
  height: 40px;
}

.el-button {
  width: 100%;
  height: 35px;
}
</style>
